package com.softao.ming.gde.internal.core.model;

import com.softao.ming.gde.core.model.IBundleVersion;

/**
 * 
 */
public class BundleVersionImpl implements IBundleVersion {
	private final String mVersion;

	/**
	 * @param version 
	 */
	public BundleVersionImpl(String version) {
		mVersion = version;
	}
	
	@Override
	public String getVersion() {
		return mVersion;
	}

	@Override
	public boolean equals(Object arg0) {
		if (arg0 == null || !(arg0 instanceof IBundleVersion)) {
			return false;
		}
		
		return mVersion.equals(((IBundleVersion)arg0).getVersion());
	}
	
	@Override
	public int hashCode() {
		return mVersion.hashCode();
	}
	
	@Override
	public String toString() {
		return mVersion;
	}
	
	/**
	 * Compares two versions, base on the schema of the version defined
	 * by <code>Eclipse</code>.
	 */
	@Override
	public int compareTo(IBundleVersion arg0) {
		String[] parts1 = mVersion.split(".");
		String[] parts2 = arg0.getVersion().split(".");
		if (parts1.length < 3 || parts2.length < 3) {
			throw new RuntimeException("Invalid bundle version.");
		}
		
		int result = Integer.parseInt(parts1[0]) - Integer.parseInt(parts2[0]);
		if (result == 0) {
			result = Integer.parseInt(parts1[1]) - Integer.parseInt(parts2[1]);
		}
		if (result == 0) {
			result = Integer.parseInt(parts1[2]) - Integer.parseInt(parts2[2]);
		}
		
		if (result == 0) {
			result = parts1.length - parts2.length;
		}
		
		if (result == 0) {
			if ("qualifier".equals(parts1[3])) {
				result = "qualifier".equals(parts2[3]) ? 0 : 1;
			} else {
				if ("qualifier".equals(parts2[3])) {
					result = -1;
				} else {
					result = Integer.parseInt(parts1[3]) - Integer.parseInt(parts2[3]);
				}
			}
		}
		return result;
	}

}
